#include "Socket.h"

ClientSock::ClientSock() {
    Sock = -1;
    memset(&SockAddress,0,sizeof(SockAddress));
    IPAddress = ""; Port = 8086;
    SendMessage = ""; ReceiveMessage = "";
}

char * ClientSock::StringToCharArray(string str) {
    char* arr = new char[str.length()];
    for (int i = 0; i < str.length(); i++) {
        arr[i] = str.at(i);
    }
    return arr;
}

string ClientSock::CharArrayToString(char *arr, int len) {
    string str = "";
    for (int i = 0; i < len; i++) {
        str += arr[i];
    }
    return str;
}

string ClientSock::showReceiveMessage() {
    return ReceiveMessage;
}

void ClientSock::SetIPAddress(string IPAddress) {
    this->IPAddress = IPAddress;
}

void ClientSock::SetPort(int Port) {
    this->Port = Port;
}

void ClientSock::SetSendMessage(string SendMessage) {
    this->SendMessage = SendMessage;
}

void ClientSock::SetSocket() {
    SockAddress.sin_family = AF_INET;
    SockAddress.sin_addr.s_addr = inet_addr(StringToCharArray(IPAddress));
    SockAddress.sin_port = htons(Port);
    connect(Sock,(sockaddr*)&SockAddress,sizeof(SockAddress));
}

bool ClientSock::Send() {
    char str[] = SendMessage;
    write(Sock,str,sizeof(str));
    return true;
}

bool ClientSock::Receive() {
    char str[256];
    read(Sock,str,sizeof(str));
    ReceiveMessage = CharArrayToString(str,sizeof(str));
    return true;
}